package com.netty.coder;

import utl.mofen.objects.JSonStream;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class JSonStreamEncoder extends MessageToByteEncoder<JSonStream> {

	@Override
	public void encode(ChannelHandlerContext ctx, JSonStream msg, ByteBuf out)
			throws Exception {	    
		String jsonString = utl.mofen.utils.GsonUtil.json2String(msg.getJSonObject());
		byte[] jsonBytes = jsonString.getBytes("utf-8");
		int jsonLength = jsonBytes.length;
		byte[] stream = msg.getStream();
		int streamLength = 0;
		if (stream!=null)
		{	
			streamLength = stream.length;
		}		
		out.writeInt(jsonLength);
		out.writeInt(streamLength);
		out.writeBytes(jsonBytes);
		
		if (streamLength>0)
		{
			out.writeBytes(stream);
		}
	}

}
